package com.sc.pattern.readwrite;

/**
 * Created  on 2018/1/7.
 *
 * @author sc
 */
public class SharedData {

    private final char[] buffer;

    private final ReadWriteLock lock = new ReadWriteLock();


    public SharedData(int size) {
        buffer = new char[size];
        for (int i = 0; i < size; i++) {
            buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        try {
            lock.readLock();
            return doRead();
        }finally {
            lock.unLockRead();
        }
    }

    public void Write(char c){
        try {
            lock.writeLock();
            doWrite(c);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unLockWrite();
        }
    }

    private void doWrite(char c) throws InterruptedException {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
            Thread.sleep(10);
        }
    }

    private char[] doRead() throws InterruptedException {
        char[] newBuf = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            newBuf[i] = buffer[i];
            Thread.sleep(50);
        }
        return newBuf;
    }
}
